#!/bin/bash

source include.sh
dst=$1
master=$2
slave=$3
build=$4
build_path=$5

# ${dst}.lck exists, no one can do anything to this box
# exists and 0 is its content, back on line, and can be used.
touch ${dst}.lck
echo "[$dst] upgrade ${dst} with $build_path"
$WGCMD $dst upgrade $build_path

flag=0

# ping 1 icmp packets every 5 seconds, retry 120 times takes 
# 600 seconds=10 minutes
retry=120
sleep_interval=5
i=0
master_ret=100
slave_ret=100

while [[ $i -lt $retry ]]; do
	ping $master -c 1 -w 1 -q >/dev/null
	master_ret=$?
	ping $slave -c 1 -w 1 -q >/dev/null
	slave_ret=$?

	ret=`expr $master_ret + $slave_ret`

	if [ $ret -eq 0 ]
		then
		((flag+=1))
		sleep 1
		echo "[$dst] ping $dst success for $flag times"
		if [ $flag -ge 30 ]
			then
			echo "[$dst] $dst is back online"
			#echo "0" > ${dst}.lck
			# check build num of box after upgrade
			build_num=`$WGCMD $dst status /system/version|xpath -q -e "/status/system/version/text()"`
			build_num=${build_num#*B*}
			if [ "$build_num" -ne "$build" ]
				then
				echo "[$dst] After upgrade, build num is still mismatched: $build_num, expect $build"
				echo "FAIL" > ${dst}.lck
				exit 1
			fi
			echo "$build_num" > ${dst}.lck
			$ENABLE_ROOT $master
			$ENABLE_ROOT $slave
			exit 0
		fi
	else
		echo "[$dst] ping to one of cluster member failed at $i retry, sleep $sleep_interval seconds and try again."
		flag=0
	    sleep $sleep_interval
	    ((i+=1))
    fi
done

echo "[$dst] Retried $retry times, all failed, $dst may be broken."
exit 1